package com.mjf.kxml.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mjf.kxml.domain.Invoices;
import com.mjf.kxml.domain.Receivable;
import com.mjf.kxml.domain.U8Meet;
import com.mjf.kxml.enums.CKApiEnum;
import com.mjf.kxml.enums.InvoiceTypeEnum;
import com.mjf.kxml.enums.SendFlagEnum;
import com.mjf.kxml.mapper.U8MeetMapper;
import com.mjf.kxml.service.InvoicesService;
import com.mjf.kxml.service.U8MeetService;
import com.mjf.kxml.util.CKHttpSendUtil;
import com.mjf.kxml.util.CKResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/6/6 15:37
 */
@Service
public class U8MeetServiceImpl extends ServiceImpl<U8MeetMapper, U8Meet> implements U8MeetService {

    @Autowired
    private InvoicesService invoicesService;

    @Override
    public Object sendAll() {
        // 查询需要推送的数据
        List<U8Meet> infoss = list(Wrappers.<U8Meet>lambdaQuery()
            .ne(U8Meet::getPullsk, SendFlagEnum.SEND_FLAG_YES.getCodes()));
        if (CollectionUtil.isNotEmpty(infoss)) {
            for (U8Meet fo : infoss) {
                List<U8Meet> infos = Collections.singletonList(fo);
                List<Invoices> invoices = invoicesService.list(Wrappers.<Invoices>lambdaQuery()
                    .in(Invoices::getRecId, infos.stream().map(U8Meet::getId).collect(Collectors.toList()))
                    .eq(Invoices::getType, Integer.parseInt(InvoiceTypeEnum.INVOICE_MEET.getCodes()))
                );
                try {
                    String soapXml = U8Meet.buildObjectXml(IdUtil.fastSimpleUUID(), infos, invoices);
                    CKResultVO ckResultVO = CKHttpSendUtil.sendXml(CKApiEnum.CK_API_PAYABLE, soapXml);
                    fo.setPullskoutstr(ckResultVO.getData());
                    fo.setPulltime(LocalDateTime.now());
                    if (ckResultVO.getSuccess()) {
                        fo.setPullsk(SendFlagEnum.SEND_FLAG_YES.getCodes());
                    } else {
                        fo.setPullsk(SendFlagEnum.SEND_FLAG_FAIL.getCodes());
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    log.error("发送应收增项数据异常 ", e);
                    fo.setPullsk(SendFlagEnum.SEND_FLAG_FAIL.getCodes());
                    fo.setPullskoutstr(e.getMessage());
                    fo.setPulltime(LocalDateTime.now());
                }
            }
            updateBatchById(infoss);
        }

        return CKResultVO.buildSuccess("S", "success", "");
    }
}
